using Avalonia.Controls;
using Avalonia.Interactivity;
using IntegratedMeasuring.ViewModels.Scheme;
using IntegratedMeasuring.Storage;
using IntegratedMeasuring.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Collections;
using IntegratedMeasuring.ViewModels.Entity;

namespace IntegratedMeasuring.Pages;

public partial class WorkbenchPage : UserControl
{
    private ProductionOrder? _currentOrder;
    
    // 表格数据绑定变量
    private List<TransItemData> _testDataList = new();
    private DataGridCollectionView? _testDataView;

    private List<TransItemData>? _mainTurn = null;

    public WorkbenchPage()
    {
        InitializeComponent();
        
        Loaded += OnLoaded;
        Unloaded += OnUnloaded;
        // 初始化CardCheckBox状态
        CardCheckBox.IsChecked = GV.IsSpotMode;
        CardCheckBox.Checked += CardCheckBox_CheckedChanged;
        CardCheckBox.Unchecked += CardCheckBox_CheckedChanged;
    }

    private void CardCheckBox_CheckedChanged(object? sender, RoutedEventArgs e)
    {
        GV.IsSpotMode = CardCheckBox.IsChecked ?? false;
    }

    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        // 页面加载时的初始化工单数据
        LoadPageData();
        
        // 初始化表格数据绑定
        InitializeTestDataGrid();
        
        // 初始化条码输入框
        InitializeBarcodeInput();
        HideModal();

        ShowModal("0000000000000");
    }

    private async void LoadPageData()
    {
        if (GV.CurrentOrderId == 0)
        {
            UpdateOrderInfo(null);
        }
        else
        {
            UpdateOrderInfo(await BaseDataStorage.Instance.QueryOrderByIdAsync(GV.CurrentOrderId));
        }
    }
    
    private void OnUnloaded(object sender, RoutedEventArgs e)
    {
        // 页面卸载时的清理工作
    }

    private void InitializeTestDataGrid()
    {
        _testDataView = new DataGridCollectionView(_testDataList);
        TestDataGrid.ItemsSource = _testDataView;
    }

    private void InitializeBarcodeInput()
    {
        // 统一使用UpdateRetestDisplay方法来控制显示
        UpdateRetestDisplay();
        
        // 如果开启了扫码，聚焦到条码输入框
        if (GV.EnableBarcodeScan)
        {
            BarcodeTextBox.Focus();
        }
    }

    /// <summary>
    /// 更新重测提示显示
    /// </summary>
    private void UpdateRetestDisplay()
    {
        if (GV.EnableBarcodeScan)
        {
            // 开启扫码：显示条码输入框和显示部分，重测提示不显示
            BarcodeInputPanel.IsVisible = true;
            BarcodeTextBox.IsVisible = true;
            BarcodeTextLabel.IsVisible = true;
            BarcodeTextValue.Text = "";
        }
        else
        {
            // 未开启扫码
            if (GV.TestedMultipleTimes > 0)
            {
                // 需要重测：显示重测提示，隐藏条码输入框
                BarcodeInputPanel.IsVisible = true;
                BarcodeTextLabel.IsVisible = false;
                BarcodeTextBox.IsVisible = false;
                BarcodeTextValue.Text = $"不良品请重测第 {GV.TestedMultipleTimes} / {GV.RetestCount} 次";
            }
            else
            {
                // 不需要重测：隐藏整个条码输入区域
                BarcodeInputPanel.IsVisible = false;
            }
        }
    }

    /// <summary>
    /// 更新表格数据
    /// </summary>
    /// <param name="newData">新的测试数据列表</param>
    public void UpdateTestData(List<TransItemData> newData)
    {
        _testDataList.Clear();
        _testDataList.AddRange(newData);
        
        // 刷新DataGrid视图
        if (_testDataView != null)
        {
            _testDataView.Refresh();
        }
    }

    /// <summary>
    /// 清空表格数据
    /// </summary>
    public void ClearTestData()
    {
        _testDataList.Clear();
        
        // 刷新DataGrid视图
        if (_testDataView != null)
        {
            _testDataView.Refresh();
        }
    }

    /// <summary>
    /// 获取当前表格数据
    /// </summary>
    /// <returns>当前测试数据列表</returns>
    public List<TransItemData> GetTestData()
    {
        return new List<TransItemData>(_testDataList);
    }

    /// <summary>
    /// 热键触发处理方法（由主窗口调用）
    /// </summary>
    public async void OnHotKeyPressed(object? sender, EventArgs e)
    {
        if (!await OnTestBefore()) return;
        HideModal();
        Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () =>
        {
            try
            {
                await LoadingHelper.ExecuteWithLoadingAsync(this, async () =>
                {
                    var result = await InstrumentControlHelper.GetTestResult();
                    if (result != null && result.TestDataDetail != null && result.TestDataDetail.Count > 0)
                    {
                        if (result.TestDataDetail.Count == _testDataList.Count + (_mainTurn != null && _mainTurn.Count != 0 ? -1 * _mainTurn.Count : 0))
                        {
                            for (int i = 0; i < _testDataList.Count; i++)
                            {
                                TestRecord? testRecord = result.TestDataDetail.Find(e =>
                                    e.Pri == _testDataList[i].Pri && e.Sec == _testDataList[i].Sec &&
                                    e.MinorTerm == _testDataList[i].MinorTerm);
                                if (testRecord == null)
                                {
                                    if (!(_testDataList[i].MinorTerm.Equals("TURN") && _testDataList[i].Sec == 0))
                                    {
                                        NotificationHelper.ShowWarning("更新失败", $"第{i + 1}行测试结果未找到");
                                    }
                                    continue;
                                }
                                else
                                {
                                    _testDataList[i].DisplayDetectionValue = testRecord.DisplayDetectionValue + testRecord.DisplayUnit;
                                    _testDataList[i].Result = testRecord.Result;
                                }
                            }
                            result.Result = result.TestDataDetail.All(x => x.Result == 1) ? 1 : 0;
                            OnTestFinished(result);
                        }
                        else
                        {
                            NotificationHelper.ShowWarning("更新失败", "测试结果数量与预期不符");
                        }
                    }
                    else
                    {
                        NotificationHelper.ShowWarning("提示", "未收到有效的测试结果。");
                    }
                }, "测试中...");
            }
            catch (Exception ex)
            {
                NotificationHelper.ShowError("测试异常", ex.Message);
            }
        });
    }

    // 测试完成时机
    private void OnTestFinished(ProductInfo result)
    {
        _testDataView?.Refresh();
        if (result.TestDataDetail != null)
        {
            List<string> newData = new List<string>();
            foreach (var testRecord in result.TestDataDetail)
            {
                if (testRecord.Result == 0) newData.Add(testRecord.MinorTerm);
            }
            string modelStr = "不良项: ";
            foreach (var se in newData.Distinct().ToList())
            {
                modelStr += se;
            }
            ShowModal(modelStr);
        }
        
        if (GV.IsSpotMode) return;
        
        // 如果开启了扫码，或者重测次数为0，直接保存记录
        if (GV.EnableBarcodeScan || GV.RetestCount == 0)
        {
            result.BarCode = BarcodeTextValue.Text;
            BarcodeTextValue.Text = "";
            
            BaseDataStorage.Instance.SaveTestProductRecordAsync(result);
            if (result.Result == 1)
            {
                _currentOrder.PassNumber += 1;
            }
            else
            {
                _currentOrder.FailNumber += 1;
            }

            MesHandler.SyncTestDetailsAsync(result, _currentOrder, _testConditions);
        }
        else
        {
            // 未开启扫码，需要处理重测逻辑
            if (GV.TestedMultipleTimes > 0)
            {
                // 这是重测，先减去上次的不良品计数
                _currentOrder.FailNumber -= 1;
                
                // 使用上次的条码
                result.BarCode = GV.LastTestProductInfo.BarCode;
                GV.TestedMultipleTimes += 1;
                
                // 保存重测记录,清理旧记录
                BaseDataStorage.Instance.SaveTestProductRecordAsync(result, GV.LastTestProductInfo.Id);
                
                if (result.Result == 1)
                {
                    // 重测通过，算作良品
                    _currentOrder.PassNumber += 1;
                    // 重测通过，重置重测计数
                    GV.TestedMultipleTimes = 0;
                    GV.LastTestProductInfo = null;
                    
                    // 更新重测显示
                    UpdateRetestDisplay();
                    MesHandler.SyncTestDetailsAsync(result, _currentOrder, _testConditions);
                }
                else
                {
                    // 重测仍然失败
                    _currentOrder.FailNumber += 1;
                    
                    // 检查是否还需要继续重测
                    if (GV.TestedMultipleTimes < GV.RetestCount)
                    {
                        // 还需要继续重测，提示用户
                        NotificationHelper.ShowWarning("重测提示", 
                            $"第{GV.TestedMultipleTimes}次重测失败，还需重测{GV.RetestCount - GV.TestedMultipleTimes}次");
                        
                        // 更新重测显示
                        UpdateRetestDisplay();
                    }
                    else
                    {
                        // 重测次数用完，最终判定为不良品
                        NotificationHelper.ShowWarning("重测完成", 
                            $"已完成{GV.RetestCount}次重测，最终判定为不良品");
                        // 重置重测计数
                        GV.TestedMultipleTimes = 0;
                        GV.LastTestProductInfo = null;
                        
                        // 更新重测显示
                        UpdateRetestDisplay();
                        MesHandler.SyncTestDetailsAsync(result, _currentOrder, _testConditions);
                    }
                }
            }
            else
            {
                // 这是第一次测试
                BaseDataStorage.Instance.SaveTestProductRecordAsync(result);
                
                if (result.Result == 1)
                {
                    // 良品，直接通过
                    _currentOrder.PassNumber += 1;
                    MesHandler.SyncTestDetailsAsync(result, _currentOrder, _testConditions);
                }
                else
                {
                    // 不良品，需要重测
                    _currentOrder.FailNumber += 1;
                    
                    if (GV.RetestCount > 0)
                    {
                        // 开始重测流程
                        GV.TestedMultipleTimes = 1;
                        GV.LastTestProductInfo = result;
                        NotificationHelper.ShowWarning("重测提示", 
                            $"测试失败，将进行{GV.RetestCount}次重测");
                        
                        // 更新重测显示
                        UpdateRetestDisplay();
                    }
                    else
                    {
                        MesHandler.SyncTestDetailsAsync(result, _currentOrder, _testConditions);
                    }
                }
            }
        }
        
        // 更新数量统计显示
        TotalCountTextBlock.Text = _currentOrder.PlanNumber.ToString();
        PassCountTextBlock.Text = _currentOrder.PassNumber.ToString();
        FailCountTextBlock.Text = _currentOrder.FailNumber.ToString();
        
        int total = _currentOrder.PlanNumber;
        int passCount = _currentOrder.PassNumber;
        double progress = total > 0 ? (double)passCount / total * 100 : 0;
        ProgressBar.Value = progress;
        ProgressTextBlock.Text = $"{progress:F1}%";
        
        // 更新数据库ProductionOrder
        BaseDataStorage.Instance.UpdateProductionOrderAsync(_currentOrder);
        
        // 只有在不需要重测时才更新LastTestProductInfo
        if (GV.EnableBarcodeScan || GV.RetestCount == 0 || result.Result == 1 || GV.TestedMultipleTimes == 0)
        {
            GV.LastTestProductInfo = result;
        }
    }
    
    // 准备测试时机
    private async Task<bool> OnTestBefore()
    {
        // TODO 扩展  测试条件的检查 /   / MES连接状况的检查
        
        // 仪器连接状态的检查
        if (!GV.IsMounted)
        {
            NotificationHelper.ShowWarning("提示", "仪器初始化未完成!");
            return false;
        }
        // 工单完成数量的检查
        if (_currentOrder == null)
        {
            NotificationHelper.ShowWarning("提示", "当前未选择工单!");
            return false;
        }
        else if (!GV.IsSpotMode && !_currentOrder.AllowOverflow && _currentOrder.PlanNumber <= _currentOrder.PassNumber)
        {
            NotificationHelper.ShowWarning("提示", "当前工单已全部完成!");
            return false;
        }

        // 对条码的检查
        if (GV.EnableBarcodeScan)
        {
            string? barcodeContent = BarcodeTextValue.Text;
            if (string.IsNullOrEmpty(barcodeContent))
            {
                NotificationHelper.ShowWarning("提示", "请输入条码!");
                return false; 
            }
        }
        return true;
    }

    private ProductionOrder? _productionOrder;
    private TestConditions? _testConditions;
    
    private async void UpdateOrderInfo(ProductionOrder? order)
    {
        _currentOrder = order;
        if (order == null)
        {
            
            
            OrderNameTextBlock.Text = "未选择工单";
            BatchNumberTextBlock.Text = "未选择周期";
            ModelNameTextBlock.Text = "未选择机种";
            GV.CurrentOrders = string.Empty;
            GV.CurrentOrderId = 0;
            GV.CurrentTestConditions = string.Empty;
            OrderNameTextBlock.Text = "未选择工单";
            ModelNameTextBlock.Text = "未选择机种";
            
            // 清空数量统计显示
            TotalCountTextBlock.Text = "0";
            PassCountTextBlock.Text = "0";
            FailCountTextBlock.Text = "0";
            
            ProgressBar.Value = 0;
            ProgressTextBlock.Text = "0%";
            ClearTestData();
            GV.IsMounted = false;
        }
        else
        {
            // 重置重测状态
            GV.TestedMultipleTimes = 0;
            GV.LastTestProductInfo = null;
            
            OrderNameTextBlock.Text = order.Name;
            BatchNumberTextBlock.Text = order.BatchNumber;
            ModelNameTextBlock.Text = order.TestConditions;
            
            GV.CurrentOrders = order.Name;
            GV.CurrentTestConditions = order.TestConditions;
            GV.CurrentOrderId = order.Id;
        
            OrderNameTextBlock.Text = order.Name;
            ModelNameTextBlock.Text = order.TestConditions;

            // 更新数量统计显示
            TotalCountTextBlock.Text = order.PlanNumber.ToString();
            PassCountTextBlock.Text = order.PassNumber.ToString();
            FailCountTextBlock.Text = order.FailNumber.ToString();

            // 计算完成进度
            int total = order.PlanNumber;
            int passCount = order.PassNumber;
            double progress = total > 0 ? (double)passCount / total * 100 : 0;
            ProgressBar.Value = progress;
            ProgressTextBlock.Text = $"{progress:F1}%";

            // 切换工单时自动加载测试项
            _testConditions = await BaseDataStorage.Instance.QueryTestConditionsByNameAsync(order.TestConditions);
            if (_testConditions != null && _testConditions.BeautifyData != null)
            {
                _mainTurn = _testConditions.BeautifyData.FindAll(item => item.MinorTerm == "TURN" && item.Sec == 0);
                // _testConditions.BeautifyData.RemoveAll(item => item.MinorTerm == "TURN" && item.Sec == 0);
                UpdateTestData(_testConditions.BeautifyData);
                if (!GV.IsMounted)
                {
                    await LoadingHelper.ExecuteWithLoadingAsync(
                        this,
                        async () => {
                            await InstrumentControlHelper.InitCondition(_testConditions.SourceData);
                        },
                        "测试文件加载中..."
                    );
                }
            }
            else
            {
                ClearTestData();
            }
            GV.IsMounted = true;
            
            // 更新重测显示
            UpdateRetestDisplay();
        }
    }

    private async void ChangeOrderButton_Click(object? sender, RoutedEventArgs e)
    {
        try
        {
            // 加载工单列表
            var orders = await BaseDataStorage.Instance.LoadProductionOrdersAsync();
            
            if (orders.Count == 0)
            {
                // 可以显示提示信息
                return;
            }

            // 创建工单选择对话框
            var dialog = new OrderSelectDialog(orders);
            var window = this.VisualRoot as Window;
            await dialog.ShowDialog(window);
            
            if (dialog.SelectedOrder != null)
            {
                GV.IsMounted = false;
                UpdateOrderInfo(dialog.SelectedOrder);
                GV.SaveGVToLocalFile();
            }

            if (GV.EnableBarcodeScan)
            {
                BarcodeTextBox.Focus();
            }
        }
        catch (Exception ex)
        {
            // 可以添加错误处理
        }
    }

    // 条码输入框键盘事件处理
    private void BarcodeTextBox_KeyDown(object? sender, Avalonia.Input.KeyEventArgs e)
    {
        if (e.Key == Avalonia.Input.Key.Enter)
        {
            // 回车键处理条码
            ProcessBarcode();
        }
    }
    
    // 扫码按钮点击事件
    private void ScanBarcodeButton_Click(object? sender, RoutedEventArgs e)
    {
        BarcodeTextBox.Text = "";
        BarcodeTextBox.Focus();
    }
    
    // 处理条码逻辑
    private async void ProcessBarcode()
    {
        string barcode = BarcodeTextBox.Text?.Trim() ?? "";
        if (string.IsNullOrEmpty(barcode))
        {
            NotificationHelper.ShowWarning("提示", "请输入条码");
            return;
        }
        // 对条码的检查
        if (GV.EnableBarcodeScan)
        {
            if (GV.EnableBarcodeValidation)
            {
                if (GV.BarcodeLength != 0 && barcode.Length != GV.BarcodeLength) 
                {
                    NotificationHelper.ShowWarning("提示", "条码长度不符合要求!");
                    BarcodeTextBox.SelectAll();
                    return; 
                }
                if (!string.IsNullOrEmpty(GV.BarcodePrefix) && !barcode.StartsWith(GV.BarcodePrefix))
                {
                    NotificationHelper.ShowWarning("提示", "条码前缀不符合要求!");
                    BarcodeTextBox.SelectAll();
                    return; 
                }
                if (!string.IsNullOrEmpty(GV.BarcodeSuffix) && !barcode.EndsWith(GV.BarcodeSuffix))
                {
                    NotificationHelper.ShowWarning("提示", "条码后缀不符合要求!");
                    BarcodeTextBox.SelectAll();
                    return; 
                }

                List<ProductInfo> productInfos =
                    await BaseDataStorage.Instance.QueryProductInfoByBarcodeAndOrder(barcode,
                        _currentOrder.Name);
                if (GV.DuplicateCodeHandling == ViewModels.Entity.GC.DuplicateCodeHandlingType.AskUser &&
                    productInfos.Count > 0)
                {
                    // 构建提示消息
                    string message = $"该条码已存在{productInfos.Count}次测试记录，最近一次于{productInfos[productInfos.Count - 1].StartTime:yyyy-MM-dd HH:mm:ss};";
                    
                    // 显示重码处理对话框
                    var window = this.VisualRoot as Window;
                    var selectedOption = await DuplicateCodeDialog.ShowDialogAsync(window, message);

                    // 根据用户选择处理
                    switch (selectedOption)
                    {
                        case ViewModels.Entity.GC.DuplicateCodeHandlingType.SaveAsNew:
                            // TODO 另存一条，继续测试
                            break;
                        case ViewModels.Entity.GC.DuplicateCodeHandlingType.OverwriteOld:
                            //  TODO  覆盖旧记录，继续测试
                            break;
                        case ViewModels.Entity.GC.DuplicateCodeHandlingType.AskUser:
                            // 重新扫码
                            BarcodeTextValue.Text = "";
                            BarcodeTextBox.Focus();
                            BarcodeTextBox.SelectAll();
                            return;
                    }
                }
            }
        }
        
        BarcodeTextValue.Text = barcode;
        // 清空输入框，准备下一次扫描
        BarcodeTextBox.Text = "";
        BarcodeTextBox.Focus();
    }
    
    // 获取当前条码
    public string GetCurrentBarcode()
    {
        return BarcodeTextBox.Text?.Trim() ?? "";
    }
    
    // 设置条码
    public void SetBarcode(string barcode)
    {
        BarcodeTextBox.Text = barcode;
    }

    private void ShowModal(string message)
    {
        ModalMessageTextBlock.Text = message;
        ModalOverlay.IsVisible = true;
    }

    private void HideModal()
    {
        ModalOverlay.IsVisible = false;
    }

    /// <summary>
    /// 点击遮罩层时关闭弹窗
    /// </summary>
    private void ModalOverlay_PointerPressed(object? sender, Avalonia.Input.PointerPressedEventArgs e)
    {
        // 如果点击的是遮罩层本身（不是弹窗内容），则关闭弹窗
        // 通过检查事件源是否是弹窗内容或其子元素来判断
        if (e.Source != ModalContentBorder && !IsDescendantOf(ModalContentBorder, e.Source))
        {
            HideModal();
            e.Handled = true;
        }
    }

    /// <summary>
    /// 点击弹窗内容时阻止事件冒泡，防止关闭弹窗
    /// </summary>
    private void ModalContentBorder_PointerPressed(object? sender, Avalonia.Input.PointerPressedEventArgs e)
    {
        // 阻止事件冒泡到遮罩层
        e.Handled = true;
    }

    /// <summary>
    /// 检查一个元素是否是另一个元素的后代
    /// </summary>
    private bool IsDescendantOf(Avalonia.Controls.Control? ancestor, object? descendant)
    {
        if (ancestor == null || descendant == null)
            return false;
        
        if (descendant == ancestor)
            return true;
        
        if (descendant is Avalonia.Visual visual)
        {
            var current = visual;
            while (current != null)
            {
                if (current == ancestor)
                    return true;
                current = current.Parent as Avalonia.Visual;
            }
        }
        return false;
    }
} 